/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-04-26 13:43:27
 * @LastEditors: icymoon911 icymoon911@163.com
 * @LastEditTime: 2024-08-09 15:16:20
 * @FilePath: \ken147258.topayClient\src\store\modules\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
  loginByOther,
  loginByPayer,
  loginByPayee,
  loginForTwiceByOther,
  loginForTwiceByPayer,
  loginForTwiceByPayee,
  logoutApiByOther,
  logoutApiByPayer,
  logoutApiByPayee,
  login as loginByWeb,
  logout as logoutByWeb,
} from "@/api/auth";
import { getUserInfoApi } from "@/api/user";
import { getUserInfo as getUserInfoByPayee } from "@/api/payee/account";
import { userInfo as getUserInfoByPayer } from "@/api/payer/user";
import { getUserInfo as getUserInfoByWeb } from "@/api/other/user";
import { resetRouter } from "@/router";
import router from "@/router";
import { store, usePayProductStore } from "@/store";

import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";
import { getLoginType as getLoginTypeFunc } from "@/utils/index";

export const useUserStore = defineStore("user", () => {
  const loginInfo = useStorage("loginInfo", {
    // loginType: getLoginTypeFunc(),
    loginType: '',
  }, sessionStorage);

  const user = useStorage(loginInfo.value.loginType + 'userData', {
    tempInfo: {},
    info: {},
  });
  // const user = useStorage('user', {
  //   info: null,
  //   tempInfo: localStorage.getItem(loginInfo.value.loginType + 'userData'),
  //   roles: [],
  //   perms: [],
  // });

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      let func = loginByWeb;
      const loginType: string = loginInfo.value.loginType

      // if (loginType === 'payer') {
      //   func = loginByPayer;
      // } else if (loginType === 'payee') {
      //   func = loginByPayee;
      // }

      func(loginData)
        .then(async (res) => {
          const { token } = res;
          localStorage.setItem(loginType + "accessToken", token); // eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          // localStorage.setItem("accessToken", token); 
          // user.value.tempInfo = {
          //   ...res,
          //   id: res.id || res.userId,
          //   username: res.username || res.mer_name || res.ms_name,
          //   nickname: res.username || res.nick_name,
          // };
          // localStorage.setItem("userData", JSON.stringify(user.value.tempInfo));

          // await usePayProductStore().loadStatus();

          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 二次登录
   * @param code 安全吗 
   * @returns 
   */
  function loginForTwice(code: string) {
    return new Promise<void>((resolve, reject) => {
      let func = loginForTwiceByOther;
      const loginType: string = loginInfo.value.loginType

      if (loginType === 'payer') {
        func = loginForTwiceByPayer;
      } else if (loginType === 'payee') {
        func = loginForTwiceByPayee;
      }

      let params = { safety_code: code };

      func(params)
        .then((res) => {
          const { twice_token } = res;
          localStorage.setItem(loginType + "accessTokenTwice", twice_token);

          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      let func = getUserInfoByWeb;
      // const loginType: string = loginInfo.value.loginType

      // if (loginType === 'payer') {
      //   func = getUserInfoByPayer;
      // } else if (loginType === 'payee') {
      //   func = getUserInfoByPayee;
      // }

      func()
        // getUserInfoApi()
        .then(data => {
          user.value.info = { ...data };

          resolve(user.value.info);
        })
        .catch((error) => {
          reject(error);
        });

      // resolve(user.value.info);
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      const loginType: string = loginInfo.value.loginType;

      // router.push({ path: '/login/' + loginType, replace: true })
      // resolve();

        let func = logoutByWeb;

        func()
          .then(() => {
            // localStorage.setItem("accessToken", "");
            // localStorage.clear();
            Object.keys(localStorage).map(key => {
              if (key.indexOf(loginType) === 0) {
                localStorage.removeItem(key);
              }
            });

            router.push({ path: '/login/' + loginType, replace: true })
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
    });
  }

  // remove token
  function resetToken() {
    console.log("resetToken");
    const loginType: string = loginInfo.value.loginType;
    return new Promise<void>((resolve) => {
      localStorage.setItem("accessToken", "");
      localStorage.clear();

      Object.keys(localStorage).map(key => {
        if (key.indexOf(loginType) === 0) {
          localStorage.removeItem(key);
        }
      });

      resetRouter(loginType);
      resolve();
    });
  }

  return {
    user,
    login,
    loginForTwice,
    getUserInfo,
    logout,
    resetToken,
    SET_LOGIN_TYPE: (type: string) => {
      loginInfo.value.loginType = type;
    },
    getLoginType: () => (loginInfo.value.loginType),
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
